package st.business.tepth.business.driverinfo;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.DriverWorkRecordBean;
import st.business.tepth.business.bean.NumberBean;
import st.business.tepth.business.bean.PagingBean;
import st.business.tepth.business.businfo.FooterNumberAdapter;
import st.business.tepth.business.history.detail.HistoryDetailDelegate;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.core.util.utilcode.util.ScreenUtils;
import st.shadow.library.ui.recycler.BaseDecoration;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-03-01 11:55
 */

public class DriverInfoDelegate extends MvpFragment<DriverInfoPresenter> implements DriverInfoContract.View {
    public static DriverInfoDelegate newInstance(String name,
                                                 String phone,
                                                 String code,
                                                 String busNumber,
                                                 String company) {
        Bundle bundle = new Bundle();
        bundle.putString("name", name);
        bundle.putString("code", code);
        bundle.putString("busNumber", busNumber);
        bundle.putString("company", company);
        bundle.putString("phone", phone);
        DriverInfoDelegate delegate = new DriverInfoDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    @BindView(R2.id.tv_tile)
    TextView mTvTitle;
    @BindView(R2.id.recycler_view_footer)
    RecyclerView mRecyclerViewFooter;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerViewContent;
    @BindView(R2.id.tv_count)
    TextView mTvCount;
    @BindView(R2.id.iv_left)
    ImageView mIvLeft;
    @BindView(R2.id.iv_right)
    ImageView mIvRight;
    @BindView(R2.id.et_date_start)
    TextView mTvDateStart;
    @BindView(R2.id.et_date_end)
    TextView mTvDateEnd;
    @BindView(R2.id.iv_driver)
    ImageView mIvDriver;
    @BindView(R2.id.tv_driver_name)
    TextView mTvDriverName;
    @BindView(R2.id.tv_driver_phone)
    TextView mTvDriverPhone;
    @BindView(R2.id.tv_work_code)
    TextView mTvCode;
    @BindView(R2.id.tv_bus_number)
    TextView mTvBusNumber;
    @BindView(R2.id.tv_subordinate_companies)
    TextView mTvCompany;

    private int mIndex = 0;
    private boolean move = false;
    private LinearLayoutManager mLinearLayoutManager;
    private DriverWorkRecordAdapter mDriverWorkRecordAdapter;
    private FooterNumberAdapter mFooterNumberAdapter;
    private boolean isRequesting = false;
    private int mPageNumber = 1;
    private final int PAGE_SIZE = 5;
    private String mDriverName;
    private String mPhone;
    private String mCode;
    private String mBusNumber;
    private String mCompany;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mDriverName = bundle.getString("name");
            mPhone = bundle.getString("phone");
            mCode = bundle.getString("code");
            mBusNumber = bundle.getString("busNumber");
            mCompany = bundle.getString("company");
        }
    }

    @Override
    public DriverInfoPresenter getPresenter() {
        return new DriverInfoPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_driver_info;
    }

    @OnClick({R2.id.tv_back})
    public void onBack() {
        pop();
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mTvTitle.setText("查看司机信息");
        mTvDriverName.setText(mDriverName);
        mTvDriverPhone.setText(String.format("电话：%s", mPhone));
        mTvCode.setText(String.format("工号：%s", mCode));
        mTvBusNumber.setText(String.format("车辆编号：%s", mBusNumber));
        mTvCompany.setText(String.format("所属公司：%s", mCompany));
        mRecyclerViewFooter.setLayoutManager(mLinearLayoutManager =
                new LinearLayoutManager(_mActivity,
                        LinearLayoutManager.HORIZONTAL, false));
        mRecyclerViewFooter.addOnScrollListener(new RecyclerViewListener());

//        HorizontalPageLayoutManager horizontalPageLayoutManager= new HorizontalPageLayoutManager(5,1);
//        mRecyclerViewContent.setLayoutManager(horizontalPageLayoutManager);
//        final PagingScrollHelper scrollHelper = new PagingScrollHelper();
//        scrollHelper.setUpRecycleView(mRecyclerViewContent);
        mRecyclerViewContent.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerViewContent.setAdapter(mDriverWorkRecordAdapter =
                new DriverWorkRecordAdapter(R.layout.item_driver_info_work_history
                        , null));
        mDriverWorkRecordAdapter.setEmptyView(R.layout.view_search_empty,
                (ViewGroup) mRecyclerViewContent.getParent());
        mRecyclerViewContent.addItemDecoration(BaseDecoration.
                create(Color.parseColor("#f0f0f0"), 1));
        mRecyclerViewContent.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                DriverWorkRecordBean driverWorkRecordBean = (DriverWorkRecordBean) adapter.getItem(position);
                if (view.getId() == R.id.tv_operation) {
                    if (driverWorkRecordBean != null) {
                        start(HistoryDetailDelegate.newInstance(driverWorkRecordBean.getRepairId()));
                    }
                    //showDetailDialog(adapter, view, position);
                }
            }
        });
        RecyclerView.ItemAnimator itemAnimator = mRecyclerViewFooter.getItemAnimator();
        if (itemAnimator != null) {
            itemAnimator.setChangeDuration(0);
        }
        mRecyclerViewFooter.setAdapter(mFooterNumberAdapter =
                new FooterNumberAdapter(R.layout.item_indictor_number, null,
                        new OnItemChooseListener<NumberBean>() {
                            @Override
                            public void onChoose(NumberBean numberBean) {
                                mPageNumber = numberBean.getNumber();
                                search(false);
                                mTvCount.setText(String.format
                                        (Locale.CHINA, "%d/%d", numberBean.getNumber(),
                                                mFooterNumberAdapter.getItemCount()));
                            }
                        }));
        onLeftClick();
        showCountEnable(false);
    }


    @OnClick(R2.id.iv_left)
    public void onLeftClick() {
        move(0);
        setBtnEnable(false, true);
    }

    @OnClick(R2.id.iv_right)
    public void onRightClick() {
        move(mFooterNumberAdapter.getItemCount() - 1);
        setBtnEnable(true, false);
    }

    private void setBtnEnable(boolean left, boolean right) {
        mIvLeft.setEnabled(left);
        mIvLeft.setBackgroundResource(left ?
                R.drawable.selector_left_number_indicator
                : R.drawable.ic_indicator_left_un_enable);

        mIvRight.setEnabled(right);
        mIvRight.setBackgroundResource(right ?
                R.drawable.selector_right_number_indicator
                : R.drawable.ic_indicator_right_un_enable);
    }

    private void move(int n) {
        if (n < 0 || n >= mFooterNumberAdapter.getItemCount()) {
            return;
        }
        mIndex = n;
        mRecyclerViewFooter.stopScroll();
        smoothMoveToPosition(n);
        mTvCount.setText(String.format
                (Locale.CHINA, "%d/%d", n + 1, mFooterNumberAdapter.getItemCount()));
    }

    @OnClick(R2.id.iv_search)
    public void onSearch() {
        mPageNumber = 1;
        search(true);
    }

    private void search(boolean isRefresh) {
        if (!isRequesting) {
            isRequesting = true;
            mDriverWorkRecordAdapter.setEmptyView(R.layout.view_loading, (ViewGroup) mRecyclerViewContent.getParent());
            mDriverWorkRecordAdapter.setNewData(null);
            mPresenter.getWorkRecord(UserManager.getInstance().getToken(),
                    mCode, mTvDateStart.getText().toString(),
                    mTvDateEnd.getText().toString(), mPageNumber, PAGE_SIZE, isRefresh
            );
        }
    }

    private void smoothMoveToPosition(int n) {
        int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerViewFooter.smoothScrollToPosition(n);
        } else if (n <= lastItem) {
            int left = mRecyclerViewFooter.getChildAt(n - firstItem).getLeft();
            mRecyclerViewFooter.smoothScrollBy(left, 0);
        } else {
            mRecyclerViewFooter.smoothScrollToPosition(n);
            move = true;
        }

    }

    private void moveToPosition(int n) {
        int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerViewFooter.scrollToPosition(n);
        } else if (n <= lastItem) {
            int left = mRecyclerViewFooter.getChildAt(n - firstItem).getLeft();
            mRecyclerViewFooter.scrollBy(left, 0);
        } else {
            mRecyclerViewFooter.scrollToPosition(n);
            move = true;
        }

    }

    @Override
    public void showData(PagingBean<DriverWorkRecordBean> pagingBean, boolean isRefresh) {
        mDriverWorkRecordAdapter.setEmptyView(R.layout.view_search_empty,
                (ViewGroup) mRecyclerViewContent.getParent());
        if (pagingBean != null) {
            mDriverWorkRecordAdapter.setNewData(pagingBean.getList());
            if (isRefresh) {
                mFooterNumberAdapter.setNewData
                        (makeNumber(pagingBean.getTotalPage()));
                mTvCount.setText(String.format
                        (Locale.CHINA, "%d/%d", 1, pagingBean.getTotalPage()));
            }
            if (pagingBean.getTotalPage() == 0) {
                showCountEnable(false);
            } else {
                showCountEnable(true);
            }
        } else {
            mDriverWorkRecordAdapter.setNewData(null);
            mFooterNumberAdapter.setNewData(null);
            showCountEnable(false);
        }
        isRequesting = false;
    }

    class RecyclerViewListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (move && newState == RecyclerView.SCROLL_STATE_IDLE) {
                move = false;
                int n = mIndex - mLinearLayoutManager.findFirstVisibleItemPosition();
                if (0 <= n && n < mRecyclerViewFooter.getChildCount()) {
                    int left = mRecyclerViewFooter.getChildAt(n).getLeft();
                    mRecyclerViewFooter.smoothScrollBy(left, 0);
                }

            }
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (move) {
                move = false;
                int n = mIndex - mLinearLayoutManager.findFirstVisibleItemPosition();
                if (0 <= n && n < mRecyclerViewFooter.getChildCount()) {
                    int left = mRecyclerViewFooter.getChildAt(n).getLeft();
                    mRecyclerViewFooter.scrollBy(left, 0);
                }
            }
        }
    }

    @OnClick(R2.id.et_date_start)
    public void onChooseDateStart() {
        final Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(_mActivity,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String date = year + "-" + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) +
                                "-" + (dayOfMonth < 10 ? ("0" + dayOfMonth) : dayOfMonth);
                        mTvDateStart.setText(date);
                        mTvDateStart.setTextColor(Color.parseColor("#333333"));
                    }
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    @OnClick(R2.id.et_date_end)
    public void onChooseDateEnd() {
        final Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(_mActivity,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String date = year + "-" + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)) +
                                "-" + (dayOfMonth < 10 ? ("0" + dayOfMonth) : dayOfMonth);
                        mTvDateEnd.setText(date);
                        mTvDateEnd.setTextColor(Color.parseColor("#333333"));
                    }
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    private void showDetailDialog(BaseQuickAdapter adapter, View view, int position) {
        DialogWorkDetailInfo dialogWorkDetailInfo = new DialogWorkDetailInfo(_mActivity);
        Window dialogWindow = dialogWorkDetailInfo.getWindow();
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
            lp.height = ScreenUtils.getScreenHeight() * 820 / 1024; // 高度
            dialogWindow.setGravity(Gravity.CENTER);
            dialogWindow.setAttributes(lp);
            dialogWorkDetailInfo.show();
        }
    }

    private List<NumberBean> makeNumber(int count) {
        final List<NumberBean> list = new ArrayList<>();
        for (int i = 1; i < count + 1; i++) {
            list.add(new NumberBean(i == 1, i));
        }
        return list;
    }

    private void showCountEnable(boolean enable) {
        if (!enable) {
            mIvLeft.setVisibility(View.INVISIBLE);
            mIvRight.setVisibility(View.INVISIBLE);
            mTvCount.setVisibility(View.INVISIBLE);
        } else {
            mIvLeft.setVisibility(View.VISIBLE);
            mIvRight.setVisibility(View.VISIBLE);
            mTvCount.setVisibility(View.VISIBLE);
        }
    }


}